package com.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.base.BaseServiceImpl;
import com.conf.web.FileDel;
import com.constant.OriginEnum;
import com.constant.PowerEnum;
import com.entity.Artical;
import com.entity.ArticalChannel;
import com.exception.ServiceException;
import com.minio.config.MinioConfig;
import com.minio.util.MinioUtil;
import com.repository.ArticalChannelRepository;
import com.repository.ArticalRepository;
import com.req.ArticalReq;
import com.req.ArticalPageReq;
import com.res.ArticalChannelRes;
import com.res.ArticalRes;
import com.base.BasePageRes;
import com.res.UserRes;
import com.service.ArticalService;
import com.util.StringUtil;
import org.apache.catalina.User;
import org.jsoup.Jsoup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.websocket.reactive.WebSocketReactiveAutoConfiguration;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.swing.plaf.basic.BasicBorders;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class ArticalServiceImpl extends BaseServiceImpl<ArticalReq, ArticalRes, ArticalRepository, Artical> implements ArticalService {
    @Autowired
    private FileDel fileDel;
    @Autowired
    private ArticalChannelRepository articalChannelRepository;
    @Autowired
    private ArticalChannelServiceImpl articalChannelService;
    @Autowired
    private ArticalRepository articalRepository;
    @Autowired
    MinioUtil minioUtil;
    @Autowired
    private MinioConfig minioConfig;

    @Override
    public BasePageRes queryPage(ArticalPageReq pageReq, UserRes userRes) {

        if (StringUtils.isEmpty(pageReq.getPage())) {
            throw new ServiceException("请传入page");
        }
        if (StringUtils.isEmpty(pageReq.getSize())) {
            throw new ServiceException("请传入size");
        }


        QueryWrapper<Artical> wrapper = new QueryWrapper<>();
        PowerEnum powerEnum = PowerEnum.codeOf(userRes.getPower());
        switch (powerEnum) {
            case Admin:
                break;
            case Users:
                wrapper.lambda().and(Wrapper -> Wrapper.eq(Artical::getUserId, userRes.getId()));
                break;
            default:
                break;
        }
        if (!StringUtils.isEmpty(pageReq.getDescre())) {
            wrapper.lambda().and(Wrapper -> Wrapper.like(Artical::getTitle, pageReq.getDescre()).or().like(Artical::getDescre, pageReq.getDescre()));
        }
        wrapper.lambda().orderByDesc(Artical::getCrDate).orderByDesc(Artical::getMoDate);

        IPage<Artical> pages = new Page<>(pageReq.getPage(), pageReq.getSize());
        IPage<Artical> articalIPage = this.page(pages, wrapper);
        BasePageRes pageRes = this.convertIpage(articalIPage, new ArticalRes());

        List<ArticalRes> articalResList = pageRes.getList();
        if(CollectionUtils.isEmpty(articalResList)){
            return pageRes;
        }
        List<Long> articalIds = new ArrayList<>();
        for (int i = 0; i < articalResList.size(); i++) {
            articalIds.add(articalResList.get(i).getId());
        }
        List<ArticalChannelRes> articalChannelRes = articalChannelRepository.queryChannel(articalIds);
        for (ArticalRes articalRes : articalResList) {
            List<ArticalChannelRes> channelRes = articalChannelRes.stream().filter(item -> {
                return Objects.equals(item.getArticalId(), articalRes.getId());
            }).collect(Collectors.toList());
            articalRes.setChannelList(channelRes);
        }

        return pageRes;
    }

    @Override
    public ArticalRes saveArtical(ArticalReq articalReq) {
        return this.handle(articalReq);
    }



    @Override
    public ArticalRes query(ArticalReq articalReq) {
        ArticalRes articalRes = super.query(articalReq);
        List<Long> articalId = Arrays.asList(articalRes.getId());
        List<ArticalChannelRes> articalChannelRes = articalChannelRepository.queryChannel(articalId);
        articalRes.setChannelList(articalChannelRes);
        return articalRes;
    }

    /**
     * 删除图片流程
     * 如果请求中没有图片路径，不执行删除，如果请求中有图片路径就删除旧的图片
     * @param articalReq
     * @return
     */
    @Override
    @Transactional(rollbackFor = Error.class)
    public ArticalRes update(ArticalReq articalReq) {
        //删除旧图片
        Artical artical = this.queryT(articalReq);
        if (!StringUtils.isEmpty(articalReq.getResourceFile())) {
            if (!Objects.equals(articalReq.getResourceFile(), artical.getResourceFile())) {
                fileDel.del(artical.getResourceFile());
            }
        }
        else{
            articalReq.setResourceFile(artical.getResourceFile());
        }

        if (!StringUtils.isEmpty(articalReq.getImgs())) {
            if (!Objects.equals(artical.getImgs(), articalReq.getImgs())) {
                fileDel.del(artical.getImgs());
            }
        }
        else{
            articalReq.setImgs(artical.getImgs());
        }

        if (!StringUtils.isEmpty(articalReq.getPreImg())) {
            if (!Objects.equals(artical.getPreImg(), articalReq.getPreImg())) {
                fileDel.del(artical.getPreImg());
            }
        }
        else{
            articalReq.setPreImg(artical.getPreImg());
        }
        //删除旧的中间频道
        QueryWrapper<ArticalChannel> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ArticalChannel::getArticalId, artical.getId());
        articalChannelRepository.delete(queryWrapper);
        //增加新的频道

        for (Long channelId : articalReq.getChannelId()) {
            ArticalChannel articalChannel = new ArticalChannel();
            articalChannel.setArticalId(artical.getId());
            articalChannel.setChannelId(channelId);
            articalChannelService.add(articalChannel);
        }
        return super.update(articalReq);
    }

    @Override
    @Transactional(rollbackFor = Error.class)
    public ArticalRes del(ArticalReq articalReq) {
        //删除图片 //还有描述中的图片等
        Artical artical = this.queryT(articalReq);
        try {
            minioUtil.deleteObject(minioConfig.getBucket(),artical.getImgs());
            minioUtil.deleteObject(minioConfig.getBucket(), artical.getPreImg());
            minioUtil.deleteObject(minioConfig.getBucket(), artical.getResourceFile());
            //删除描述中的图片
           minioUtil.deleteObject(minioConfig.getBucket(),StringUtil.tagFileUrl(artical.getDescre()));
           minioUtil.deleteObject(minioConfig.getBucket(),StringUtil.tagFileUrl(artical.getOtherPre()));
           minioUtil.deleteObject(minioConfig.getBucket(),StringUtil.tagFileUrl(artical.getOtherResourceFile()));

        } catch (Exception e) {
            e.printStackTrace();
        }

        QueryWrapper<ArticalChannel> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ArticalChannel::getArticalId, artical.getId());
        articalChannelRepository.delete(queryWrapper);
        return super.del(articalReq);
    }

    @Override
    @Transactional(rollbackFor = Error.class)
    public ArticalRes add(ArticalReq articalReq) {
        ArticalRes articalRes = super.add(articalReq);
        if(articalReq.getChannelId() != null){
        for (Long channelId : articalReq.getChannelId()) {
            ArticalChannel articalChannel = new ArticalChannel();
            articalChannel.setArticalId(articalRes.getId());
            articalChannel.setChannelId(channelId);
            articalChannelService.add(articalChannel);
        }}
        return articalRes;
    }

    @Override
    public boolean replaceWordPressUrl(String oldUrl, String newUrl) {
        try {
            articalRepository.replaceWordPressUrl(oldUrl,newUrl, OriginEnum.JINXIUJIAQI.getCode());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

}
